<template>
	<view class="page">
		<!-- 地图容器 -->
		<view class="map-container">
			<map 
				id="houseMap" 
				class="map" 
				:latitude="latitude" 
				:longitude="longitude" 
				:polygons="polygons" 
				:markers="markers" 
				:scale="scale"
				@tap="handleMapTap"
				@markertap="handleMarkerTap"
				@regionchange="handleRegionChange"
				v-if="latitude"
			>
				<!-- 地图控制按钮 -->
				<cover-view class="map-controls">
					<cover-view class="control-btn" @click="resetView" v-if="currentLevel > 0">
						<cover-image src="https://image.srea.org.cn/xcx/icon/icon-back.png" class="control-icon"></cover-image>
						<cover-view class="control-text">返回</cover-view>
					</cover-view>
					
					<cover-view class="level-indicator">
						<cover-view class="level-text">{{ levelText }}</cover-view>
					</cover-view>
				</cover-view>
				
				<!-- 房源统计信息 -->
				<cover-view class="house-stats" v-if="houseStats.total > 0">
					<cover-view class="stats-text">共{{ houseStats.total }}套房源</cover-view>
				</cover-view>
			</map>
		</view>
		
		<!-- 底部房源列表 -->
		<view class="house-list" v-if="houseList.length > 0">
			<view class="list-header">
				<text class="list-title">{{ currentAreaName }}房源</text>
				<text class="list-count">共{{ houseList.length }}个</text>
			</view>
			<scroll-view class="list-content" scroll-y>
				<view 
					class="house-item" 
					v-for="house in houseList" 
					:key="house.id"
					@click="goToHouseDetail(house)"
				>
					<view class="house-info">
						<text class="house-name">{{ house.title }}</text>
						<text class="house-price">{{ formatPrice(house.price) }}</text>
						<text class="house-area">{{ house.area }}㎡</text>
					</view>
					<view class="house-status" :class="getStatusClass(house.sell_type)">
						{{ house.sell_type_display }}
					</view>
				</view>
			</scroll-view>
		</view>
		
		<!-- 加载状态 -->
		<view class="loading" v-if="loading">
			<text>加载中...</text>
		</view>
	</view>
</template>

<script setup>
	import { ref, computed } from 'vue';
	import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
	import { useUserInfoStore, useIndexStore } from '@/store/index';
	import { getAreasForCity, getPolygonForArea, plateProductsForArea } from '@/common/api/houses';

	const userInfoStore = useUserInfoStore();
	const indexStore = useIndexStore();
	
	// 地图相关数据
	const latitude = ref(31.230416); // 上海中心坐标
	const longitude = ref(121.473701);
	const scale = ref(10);
	const mapContext = ref(null);
	
	// 地图层级控制
	const currentLevel = ref(0); // 0: 上海区域, 1: 板块, 2: 房源
	const currentAreaCode = ref('');
	const currentAreaName = ref('上海');
	const selectedPlate = ref(null);
	
	// 地图数据
	const polygons = ref([]);
	const markers = ref([]);
	const houseList = ref([]);
	const loading = ref(false);
	
	// 区域数据
	const areas = ref([]);
	const plates = ref([]);
	
	// 房源统计
	const houseStats = computed(() => {
		return {
			total: houseList.value.length
		};
	});
	
	// 层级文本
	const levelText = computed(() => {
		const texts = ['上海区域', '板块详情', '房源详情'];
		return texts[currentLevel.value] || '上海区域';
	});

	onLoad(() => {
		// 创建地图上下文
		setTimeout(() => {
			mapContext.value = uni.createMapContext('houseMap');
		}, 100);

		// 直接初始化地图，不依赖登录检查
		uni.$check_and_login(async () => {
			await initMap();
		})
	});

	// 初始化地图
	const initMap = async () => {
		loading.value = true;
		try {
			// 获取上海区域数据
			await loadAreas();
			// 加载区域多边形和标记
			await loadAreaData();
		} catch (error) {
			console.error('地图初始化失败:', error);
			uni.showToast({
				title: '地图加载失败',
				icon: 'none'
			});
		} finally {
			loading.value = false;
		}
	};

	// 加载区域数据
	const loadAreas = async () => {
		try {
			const res = await getAreasForCity(indexStore.nowCityCode, 'area_share');
			if (res.status === 0) {
				areas.value = res.detail;
			} else {
				// 使用演示数据
				areas.value = getDemoAreas();
			}
			// areas.value = getDemoAreas();
		} catch (error) {
			console.error('加载区域数据失败:', error);
			// 使用演示数据
			areas.value = getDemoAreas();
		}
	};

	// 获取演示区域数据
	const getDemoAreas = () => {
		const demoData = [
			{
				label: '浦东新区',
				value: 'pudong',
				polygon: {
					points: [
						[121.4, 31.1], [121.6, 31.1], [121.6, 31.3], [121.4, 31.3], [121.4, 31.1]
					],
					children: [
						{
							title: '陆家嘴',
							center: [121.5, 31.2],
							count: 15
						},
						{
							title: '张江',
							center: [121.55, 31.15],
							count: 8
						}
					]
				}
			},
			{
				label: '黄浦区',
				value: 'huangpu',
				polygon: {
					points: [
						[121.45, 31.2], [121.5, 31.2], [121.5, 31.25], [121.45, 31.25], [121.45, 31.2]
					],
					children: [
						{
							title: '外滩',
							center: [121.47, 31.22],
							count: 12
						},
						{
							title: '南京路',
							center: [121.48, 31.23],
							count: 6
						}
					]
				}
			}
		];
		return demoData;
	};

	// 加载区域地图数据
	const loadAreaData = async () => {
		if (areas.value.length === 0) return;
		
		try {
			// 为每个区域加载多边形数据
			const areaPromises = areas.value.map(async (area) => {
				// 如果已经有polygon数据（演示数据），直接使用
				if (area.polygon) {
					return {
						...area,
						markers: createAreaMarkers(area.polygon.children, area)
					};
				}
				
				// 否则从API加载
				const polygonRes = await getPolygonForArea(area.value);
				if (polygonRes.status === 0) {
					return {
						...area,
						polygon: polygonRes.detail,
						markers: createAreaMarkers(polygonRes.detail.children, area)
					};
				}
				return area;
			});
			
			const areaData = await Promise.all(areaPromises);
			areas.value = areaData;
			
			// 设置地图多边形和标记
			setupMapData();
		} catch (error) {
			console.error('加载区域地图数据失败:', error);
			// 即使出错也要设置地图数据
			setupMapData();
		}
	};

	// 创建区域标记
	const createAreaMarkers = (children, area) => {
		return children.map((child, index) => ({
			id: 10000 + index, // 使用数字ID
			longitude: child.center[0],
			latitude: child.center[1],
			width: 30,
			height: 30,
			callout: {
				content: `${child.title}\n${child.count || 0}套房源`,
				color: '#FFFFFF',
				fontSize: 12,
				bgColor: '#007235',
				borderRadius: 4,
				padding: 8,
				display: 'ALWAYS'
			},
			data: {
				type: 'area',
				areaCode: area.value,
				areaName: area.label,
				plateName: child.title,
				plateData: child
			}
		}));
	};

	// 创建区域中心标记（用于点击区域）
	const createAreaCenterMarkers = (area) => {
		if (!area.polygon || !area.polygon.points) {
			return [];
		}
		
		// 计算区域中心点
		const points = area.polygon.points;
		const centerLng = points.reduce((sum, point) => sum + Number(point[0]), 0) / points.length;
		const centerLat = points.reduce((sum, point) => sum + Number(point[1]), 0) / points.length;
		
		// 计算总房源数
		const totalCount = area.polygon.children ? 
			area.polygon.children.reduce((sum, child) => sum + (child.count || 0), 0) : 0;
		
		const marker = {
			id: 20000 + areas.value.indexOf(area), // 使用数字ID
			longitude: centerLng,
			latitude: centerLat,
			width: 40,
			height: 40,
			callout: {
				content: `${area.label}\n共${totalCount}套房源`,
				color: '#FFFFFF',
				fontSize: 14,
				bgColor: '#007235',
				borderRadius: 6,
				padding: 10,
				display: 'ALWAYS'
			},
			data: {
				type: 'area_center',
				areaCode: area.value,
				areaName: area.label,
				areaData: area
			}
		};
		
		return [marker];
	};

	// 设置地图数据
	const setupMapData = () => {
		// 合并所有区域的多边形
		const allPolygons = [];
		const allMarkers = [];
		
		areas.value.forEach(area => {
			if (area.polygon) {
				// 添加区域多边形
				const polygonPoints = area.polygon.points.map(point => ({
					longitude: Number(point[0]),
					latitude: Number(point[1])
				}));
				
				allPolygons.push({
					points: polygonPoints,
					strokeColor: '#007235',
					fillColor: '#00723530',
					strokeWidth: 2
				});
				
				// 初始状态只显示区域中心标记，不显示板块标记
				if (currentLevel.value === 0) {
					const centerMarkers = createAreaCenterMarkers(area);
					allMarkers.push(...centerMarkers);
				} else {
					// 如果已经进入板块视图，显示板块标记
					if (area.markers) {
						allMarkers.push(...area.markers);
					}
				}
			}
		});
		
		polygons.value = allPolygons;
		markers.value = allMarkers;
		
		// 调整地图视野
		adjustMapView();
	};

	// 调整地图视野
	const adjustMapView = () => {
		// 延迟执行，确保地图上下文已准备好
		setTimeout(() => {
			if (!mapContext.value) {
				mapContext.value = uni.createMapContext('houseMap');
			}
			
			const points = [];
			areas.value.forEach(area => {
				if (area.polygon) {
					area.polygon.points.forEach(point => {
						points.push({
							longitude: Number(point[0]),
							latitude: Number(point[1])
						});
					});
				}
			});
			
			if (points.length > 0 && mapContext.value) {
				mapContext.value.includePoints({
					points: points,
					padding: [50, 50, 50, 50]
				});
			}
		}, 200);
	};

	// 地图点击事件
	const handleMapTap = (e) => {
		// 可以在这里处理地图空白区域点击
	};

	// 标记点击事件
	const handleMarkerTap = async (e) => {
		const markerId = e.detail.markerId;
		const marker = markers.value.find(m => m.id === markerId);
		
		if (!marker || !marker.data) return;
		
		const { type, areaCode, areaName, plateName, plateData, areaData } = marker.data;
		
		if (type === 'area_center') {
			// 点击区域中心标记，进入板块视图
			await enterPlateView(areaCode, areaName, null, areaData);
		} else if (type === 'plate_center') {
			// 点击板块中心标记，显示该板块的房源
			await enterHouseView(plateData);
		} else if (type === 'house') {
			// 点击房源标记，进入详情页
			goToHouseDetail(plateData);
		}
	};

	// 进入板块视图
	const enterPlateView = async (areaCode, areaName, plateName, areaData) => {
		loading.value = true;
		currentLevel.value = 1;
		currentAreaCode.value = areaCode;
		currentAreaName.value = areaName;
		selectedPlate.value = areaData;
		
		try {
			// 加载板块数据
			const plateRes = await plateProductsForArea(areaCode);
			if (plateRes.status === 0) {
				plates.value = plateRes.detail;
			} else {
				// 使用演示数据
				plates.value = getDemoPlates(areaCode);
			}
			setupPlateView();
		} catch (error) {
			console.error('加载板块数据失败:', error);
			// 使用演示数据
			plates.value = getDemoPlates(areaCode);
			setupPlateView();
		} finally {
			loading.value = false;
		}
	};

	// 获取演示板块数据
	const getDemoPlates = (areaCode) => {
		const demoData = {
			pudong: [
				{
					title: '陆家嘴板块',
					list: [
						{
							id: '1',
							title: '汤臣一品',
							lng: 121.5,
							lat: 31.2,
							price: [150000, 200000],
							area: '200-300',
							sell_type: '在售中',
							sell_type_display: '在售中'
						},
						{
							id: '2',
							title: '中粮海景壹号',
							lng: 121.51,
							lat: 31.21,
							price: [120000, 180000],
							area: '180-280',
							sell_type: '在售中',
							sell_type_display: '在售中'
						}
					]
				},
				{
					title: '张江板块',
					list: [
						{
							id: '3',
							title: '张江汤臣豪园',
							lng: 121.55,
							lat: 31.15,
							price: [80000, 120000],
							area: '120-200',
							sell_type: '认购中',
							sell_type_display: '认购中'
						}
					]
				}
			],
			huangpu: [
				{
					title: '外滩板块',
					list: [
						{
							id: '4',
							title: '外滩源',
							lng: 121.47,
							lat: 31.22,
							price: [100000, 150000],
							area: '150-250',
							sell_type: '待销售',
							sell_type_display: '待销售'
						}
					]
				}
			]
		};
		return demoData[areaCode] || [];
	};

	// 设置板块视图
	const setupPlateView = () => {
		// 创建板块标记
		const plateMarkers = [];
		plates.value.forEach((plate, plateIndex) => {
			// 先添加板块中心标记
			if (plate.list && plate.list.length > 0) {
				// 计算板块中心点
				const centerLng = plate.list.reduce((sum, house) => sum + house.lng, 0) / plate.list.length;
				const centerLat = plate.list.reduce((sum, house) => sum + house.lat, 0) / plate.list.length;
				
				plateMarkers.push({
					id: 30000 + plateIndex, // 使用数字ID
					longitude: centerLng,
					latitude: centerLat,
					width: 35,
					height: 35,
					callout: {
						content: `${plate.title}\n${plate.list.length}个楼盘`,
						color: '#FFFFFF',
						fontSize: 12,
						bgColor: '#007235',
						borderRadius: 6,
						padding: 8,
						display: 'ALWAYS'
					},
					data: {
						type: 'plate_center',
						plateIndex: plateIndex,
						plateData: plate
					}
				});
			}
		});
		
		markers.value = plateMarkers;
		polygons.value = []; // 隐藏区域多边形
		
		// 调整地图视野到板块
		if (plateMarkers.length > 0) {
			const points = plateMarkers.map(marker => ({
				longitude: marker.longitude,
				latitude: marker.latitude
			}));
			
			setTimeout(() => {
				if (!mapContext.value) {
					mapContext.value = uni.createMapContext('houseMap');
				}
				
				if (mapContext.value) {
					mapContext.value.includePoints({
						points: points,
						padding: [50, 50, 50, 50]
					});
				}
			}, 200);
		}
		
		// 设置房源列表
		houseList.value = plates.value.flatMap(plate => plate.list);
	};

	// 进入房源视图
	const enterHouseView = (plateData) => {
		currentLevel.value = 2;
		currentAreaName.value = plateData.title;
		
		// 显示该板块的所有房源标记
		const houseMarkers = plateData.list.map((house, index) => ({
			id: 40000 + index, // 使用数字ID
			longitude: house.lng,
			latitude: house.lat,
			width: 20,
			height: 20,
			callout: {
				content: house.title,
				color: '#FFFFFF',
				fontSize: 10,
				bgColor: getHouseStatusColor(house.sell_type),
				borderRadius: 10,
				padding: 4,
				display: 'ALWAYS'
			},
			data: {
				type: 'house',
				houseData: house
			}
		}));
		
		markers.value = houseMarkers;
		houseList.value = plateData.list;
		
		// 调整地图视野到房源
		if (houseMarkers.length > 0) {
			const points = houseMarkers.map(marker => ({
				longitude: marker.longitude,
				latitude: marker.latitude
			}));
			
			setTimeout(() => {
				if (!mapContext.value) {
					mapContext.value = uni.createMapContext('houseMap');
				}
				
				if (mapContext.value) {
					mapContext.value.includePoints({
						points: points,
						padding: [50, 50, 50, 50]
					});
				}
			}, 200);
		}
	};

	// 重置视图
	const resetView = () => {
		if (currentLevel.value === 2) {
			// 从房源视图返回板块视图
			currentLevel.value = 1;
			setupPlateView();
		} else if (currentLevel.value === 1) {
			// 从板块视图返回区域视图
			currentLevel.value = 0;
			currentAreaCode.value = '';
			currentAreaName.value = '上海';
			selectedPlate.value = null;
			houseList.value = [];
			setupMapData();
		}
	};

	// 地图区域变化事件
	const handleRegionChange = (e) => {
		// 可以在这里处理地图缩放、移动等事件
	};

	// 获取房源状态颜色
	const getHouseStatusColor = (sellType) => {
		const colors = {
			'待销售': '#5FAADD',
			'认购中': '#0F49BC',
			'在售中': '#D81C03'
		};
		return colors[sellType] || '#999999';
	};

	// 获取房源状态样式类
	const getStatusClass = (sellType) => {
		const classes = {
			'待销售': 'status-pending',
			'认购中': 'status-subscribe',
			'在售中': 'status-selling'
		};
		return classes[sellType] || 'status-default';
	};

	// 格式化价格
	const formatPrice = (price) => {
		if (!price || !Array.isArray(price)) return '价格待定';
		const [min, max] = price;
		if (min && max) {
			return `${(min/10000).toFixed(1)}-${(max/10000).toFixed(1)}万`;
		} else if (min) {
			return `${(min/10000).toFixed(1)}万起`;
		}
		return '价格待定';
	};

	// 跳转到房源详情
	const goToHouseDetail = (house) => {
		uni.navigateTo({
			url: `/pages/product/detail/index?productId=${house.id}&title=${house.title}`
		});
	};

	// 分享到好友
	onShareAppMessage(() => {
		return {
			title: '新房超市-地图找房',
			path: `/pages/products/map/test?puid=${userInfoStore.userInfo.id}`,
			imageUrl: '',
		}
	})

	// 分享到朋友圈
	onShareTimeline(() => {
		return {
			title: '新房超市-地图找房',
			query: `puid=${userInfoStore.userInfo.id}`,
			imageUrl: '',
		}
	})
</script>

<style lang="scss" scoped>
.page {
	height: 100vh;
	display: flex;
	flex-direction: column;
	background-color: #f5f5f5;
}

.map-container {
	position: relative;
	height: 100%;
	.map {
		width: 100%;
		height: 100%;
	}
	
	.map-controls {
		position: absolute;
		top: 20rpx;
		left: 20rpx;
		z-index: 10;
		
		.control-btn {
			display: flex;
			align-items: center;
			background: rgba(255, 255, 255, 0.9);
			border-radius: 8rpx;
			padding: 10rpx 16rpx;
			margin-bottom: 10rpx;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
			
			.control-icon {
				width: 24rpx;
				height: 24rpx;
				margin-right: 8rpx;
			}
			
			.control-text {
				font-size: 24rpx;
				color: #333;
			}
		}
		
		.level-indicator {
			background: rgba(0, 114, 53, 0.9);
			border-radius: 8rpx;
			padding: 8rpx 16rpx;
			
			.level-text {
				font-size: 24rpx;
				color: #fff;
			}
		}
	}
	
	.house-stats {
		position: absolute;
		bottom: 20rpx;
		left: 20rpx;
		right: 20rpx;
		z-index: 10;
		
		.stats-text {
			background: rgba(0, 114, 53, 0.9);
			color: #fff;
			padding: 12rpx 20rpx;
			border-radius: 8rpx;
			font-size: 24rpx;
			text-align: center;
		}
	}
}

.house-list {
	height: 400rpx;
	background: #fff;
	border-top: 1rpx solid #eee;
	
	.list-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		border-bottom: 1rpx solid #eee;
		
		.list-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}
		
		.list-count {
			font-size: 24rpx;
			color: #666;
		}
	}
	
	.list-content {
		height: calc(100% - 80rpx);
		
		.house-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			border-bottom: 1rpx solid #f0f0f0;
			
			&:last-child {
				border-bottom: none;
			}
			
			.house-info {
				flex: 1;
				
				.house-name {
					display: block;
					font-size: 28rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 8rpx;
				}
				
				.house-price {
					display: block;
					font-size: 24rpx;
					color: #ff6b35;
					margin-bottom: 4rpx;
				}
				
				.house-area {
					font-size: 22rpx;
					color: #666;
				}
			}
			
			.house-status {
				padding: 6rpx 12rpx;
				border-radius: 4rpx;
				font-size: 20rpx;
				color: #fff;
				
				&.status-pending {
					background-color: #5FAADD;
				}
				
				&.status-subscribe {
					background-color: #0F49BC;
				}
				
				&.status-selling {
					background-color: #D81C03;
				}
				
				&.status-default {
					background-color: #999999;
				}
			}
		}
	}
}

.loading {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(255, 255, 255, 0.8);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 1000;
	
	text {
		font-size: 28rpx;
		color: #666;
	}
}
</style>
